<template>
	<div>
		<van-nav-bar left-text="我的信息" left-arrow @click-left="$router.back()">
		</van-nav-bar>
		<div class="imgs" @click="addimg">
			<van-image width="100" height="100" :src="imgurl" round />
			<p class="photo">更新头像</p>
		</div>
		<div>
			<van-field v-model="nickname" label="昵称" />
			<van-field v-model="signatures" label="个性签名" />
			<van-field v-model="pasword" label="修改密码" />
		</div>
		<van-button type="primary" round @click="saveinfo">保存</van-button>
	</div>
</template>
<script>
let imgupdata = null;
export default {
	data() {
		return {
			nickname: "",
			signatures: "",
			pasword: "",
			imgurl: "",
		};
	},
	mounted() {
		this.$parent.showTabbar = false;
	},
	destroyed() {
		this.$parent.showTabbar = true;
	},
	methods: {
		saveinfo() {
			let save = {
				userimg: this.imgurl,
				name: this.nickname,
				signatures: this.signatures,
				pasword: this.pasword,
			};
			console.log(save);
			localStorage.setItem("userMessage", JSON.stringify(save));
			this.$router.push("/mine");
		},
		// 添加图片
		addimg() {
			if (!imgupdata) {
				// 生成文件上传的控件
				imgupdata = document.createElement("input");
				imgupdata.setAttribute("type", "file");
				imgupdata.style.display = "none";
				//  监听事件
				if (window.addEventListener) {
					// ie9及上的浏览器识别
					imgupdata.addEventListener("change", this.uploadfile, false);
				} else {
					// ie8及以下浏览器识别
					imgupdata.attachEvent("onchange", this.uploadfile);
				}
				document.body.appendChild(imgupdata);
			}
			imgupdata.click();
		},
		uploadfile(el) {
			if (el && el.target && el.target.files && el.target.files.length > 0) {
				console.log(el);
				const files = el.target.files[0];
				// 判断是否为图片格式
				if (files.type.indexOf("image") === -1) {
					console.log("请选择图片文件");
				} else {
					const that = this;
					const reader = new FileReader(); //创建读取文件对象
					// 发起异步请求，读取文件
					reader.readAsDataURL(el.target.files[0]);
					// 文件读取成功
					reader.onload = function () {
						that.imgurl = this.result;
						// console.log(this.result);
						// 数据传到后台
						// const formDate=new FormData();
						// 传到后台的数据
						// formDate.append('file',files);
						// console.log(formDate);
					};
				}
			}
		},
	},
};
</script>
<style scoped lang="scss">
.imgs {
	text-align: center;
	.photo {
		color: rgb(252, 121, 121);
	}
}
.van-button {
	width: calc(100% - 40px);
	margin: 20px 20px;
	font-size: 20px;
	background-color: #1baeae;
}
</style>
